package com.ol.edu.server.controller.course;


import com.github.pagehelper.PageInfo;
import com.ol.edu.server.entity.Course;
import com.ol.edu.server.entity.CourseVO;
import com.ol.edu.server.entity.ResponseResult;
import com.ol.edu.server.service.course.CourseService;
import com.ol.edu.server.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author Roger
 * @date 2020/9/5 14:05
 * @description
 */
@RestController
@RequestMapping("/course")
@CrossOrigin
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /*
       分页获取课程列表数据&多条件查询
    */
    @RequestMapping(value = "/findAllCourse")
    public ResponseResult findCourseByConditioin(@RequestBody CourseVO courseVo) {

        PageInfo<Course> pageInfo = courseService.findCourseByConditioin(courseVo);
        if (pageInfo.getTotal() == 0) {
            return new ResponseResult(true, 200, "没有数据", null);
        } else {
            return new ResponseResult(true, 200, "查询成功", pageInfo);
        }

    }

    /*
        图片上传
     */
    @RequestMapping("/courseUpload")
    public ResponseResult fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        Map map = UploadUtils.upload(file);
        // 如果map没有数据表示上传失败
        if (map.isEmpty()) {
            return new ResponseResult(false, 200, "上传失败", map);
        }
        return new ResponseResult(true, 200, "上传成功", map);
    }

    /*
        新建课程或修改课程
     */
    @RequestMapping("/saveOrUpdateCourse")
    public ResponseResult saveOrUpdateCourse(@RequestBody CourseVO courseVo) {
        //根据传入的参数是否有ID值判断是新增还是更新操作
        if (courseVo.getId() == null) {
            //新增
            courseService.addCourse(courseVo);
            return new ResponseResult(true, 200, "添加课程成功", null);
        } else {
            //更新
            courseService.updateCourse(courseVo);
            return new ResponseResult(true, 200, "修改课程成功", null);
        }

    }

    /*
        根据id查询课程信息
     */
    @RequestMapping("/findCourseById")
    public ResponseResult findCourseById(Integer id) {
        CourseVO courseVO = courseService.findCourseById(id);
        return new ResponseResult(true, 200, "查询课程成功", courseVO);
    }

    /*
        修改课程状态
     */
    @RequestMapping("/updateCourseStatus")
    public ResponseResult updateCourseStatus(Integer id, Integer status) {
        Map<String, Integer> map = courseService.updateCourseStatus(id, status);
        return new ResponseResult(true, 200, "修改课程状态成功", map);
    }

}
